import axios from 'axios'

const http = axios.create({
  baseURL: '/mock',
})

class StatusError extends Error {
  constructor(message) {
    super(message)
    this.name = 'Status Error'
  }
}

class CodeError extends Error {
  constructor(message) {
    super(message)
    this.name = 'Code Error'
  }
}

http.interceptors.response.use((res) => {
  const { method, baseURL, url } = res.config
  console.log('[' + method + ']', baseURL + url)
  if (res.status === 200) {
    const body = res.data
    if (body.code === 0) {
      return body.data
    } else {
      return Promise.reject(new CodeError(body.code))
    }
  } else {
    return Promise.reject(new StatusError(res.status))
  }
})

export const handleHttpError = (error) => {
  switch (error.name) {
    case 'Status Error':
      console.log('状态码错误', error.message)
      break
    case 'Code Error':
      console.log('对照码错误', error.message)
      break
    default:
      // 'Error'
      console.log('网络错误', error.message)
  }
}

export default http
